package com.aleaho.cftrack;


import android.annotation.TargetApi;
import android.app.Application;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;

import com.aleaho.cftrack.activity.MainActivity;
import com.aleaho.cftrack.db.DBHelper;
import com.aleaho.cftrack.db.gen.DaoMaster;
import com.aleaho.cftrack.db.gen.DaoSession;
import com.aleaho.cftrack.db.service.LastLoginService;
import com.aleaho.cftrack.db.service.UserService;
import com.aleaho.cftrack.font.NewIcon;
import com.aleaho.cftrack.http.entity.LoginEntity;
import com.aleaho.cftrack.utils.CommonUtil;
import com.aleaho.cftrack.utils.Constants;
import com.aleaho.cftrack.utils.JsonTool;
import com.aleaho.cftrack.utils.TrackConsts;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.LocRequest;
import com.baidu.trace.model.BaseRequest;
import com.baidu.trace.model.LocationMode;
import com.beardedhen.androidbootstrap.TypefaceProvider;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2017/8/19.
 */

public class CFTrackApplication extends Application {
    private static CFTrackApplication instance;

    public static CFTrackApplication getInstance() {
        return instance;
    }

    private AtomicInteger mSequenceGenerator = new AtomicInteger();


    private LocRequest locRequest = null;
    private Notification notification = null;
    private Context mContext = null;

    private SharedPreferences trackConf = null;

    /**
     * 轨迹服务客户端
     */
    public LBSTraceClient mClient = null;

    /**
     * 轨迹服务
     */
    public Trace mTrace = null;


    private LoginEntity loginEntity = null;
    private String entityName = "unKnown";

    /**
     * 本地数据库操作
     */
    private DaoMaster.OpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;


    /**
     * 屏幕的宽度
     */
    private int screenWidth = 0;
    /**
     * 屏幕的高度
     */
    private int screenHeight = 0;


    private boolean isNeedObjectStorage = false;

    /**
     * 服务是否开启标识
     */
    public boolean isTraceStarted = false;

    /**
     * 采集是否开启标识
     */
    public boolean isGatherStarted = false;


    public boolean isRegisterReceiver = false;

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = getApplicationContext();
        // 若为创建独立进程，则不初始化成员变量
        if ("com.aleaho.cftrack:remote".equals(CommonUtil.getCurProcessName(mContext))) {
            return;
        }

        TypefaceProvider.registerDefaultIconSets();
        TypefaceProvider.registerCustomIconSet(new NewIcon());
        SDKInitializer.initialize(mContext);

        getScreenSize();
        initNotification();
        setDataBase();

        //初始化鹰眼的客户端
        initClient();
        //初始化鹰眼服务
        initTrace();

        trackConf = getSharedPreferences("travel", MODE_PRIVATE);

        locRequest = new LocRequest(Constants.SERVICEID);
        instance = this;
    }


    /**
     * 退出账号，清楚本地信息
     */
    public void logout() {
        LastLoginService.deleteAll();
        this.entityName = "";
        this.loginEntity = null;
    }


    //region   初始化鹰眼客户端和鹰眼服务，同时生成通知事件。

    /**
     * 初始化鹰眼客户端
     */
    private void initClient() {

        mClient = new LBSTraceClient(mContext);
        mClient.setLocationMode(LocationMode.High_Accuracy);
        mClient.setInterval(TrackConsts.DEFAULT_GATHER_INTERVAL, TrackConsts.DEFAULT_PACK_INTERVAL);
    }


    /**
     * 初始化鹰眼服务
     */
    private void initTrace() {

        mTrace = new Trace(Constants.SERVICEID, this.entityName, isNeedObjectStorage);
        mTrace.setNotification(notification);
    }


    /**
     * 初始化请求公共参数
     *
     * @param request
     */
    public void initRequest(BaseRequest request) {
        request.setTag(getTag());
        request.setServiceId(Constants.SERVICEID);
    }


    /**
     * @return
     */
    public int getTag() {
        return mSequenceGenerator.incrementAndGet();
    }


    //endregion

    // region   初始化程序通知
    @TargetApi(16)
    private void initNotification() {
        Notification.Builder builder = new Notification.Builder(mContext);
        Intent notificationIntent = new Intent(mContext, MainActivity.class);
        Bitmap icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon_logo);

        builder.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
                .setLargeIcon(icon)
                .setSmallIcon(R.drawable.icon_logo)
                .setContentTitle(Constants.NOTIFICATION_NAME)
                .setContentText(Constants.NOTIFICATION_MESSAGE)
                .setWhen(System.currentTimeMillis());

        notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
    }

    // endregion

    //region 屏幕尺寸

    /**
     * 获得屏幕的尺寸（单位：像素）
     */
    private void getScreenSize() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
    }


    public int getScreenWidth() {
        return screenWidth;
    }

    public int getScreenHeight() {
        return screenHeight;
    }
    //endregion

    //region 本地数据操作，获得DAO，Session，DB

    /**
     * 设置greenDao
     */
    private void setDataBase() {
        mHelper = new DBHelper(this, "cftrack-db");

        db = mHelper.getWritableDatabase();

        mDaoMaster = new DaoMaster(db);

        mDaoSession = mDaoMaster.newSession();
    }


    /**
     * 获得DaoSession.
     *
     * @return mDaoSession
     */
    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    /**
     * 获得数据库。
     *
     * @return db
     */
    public SQLiteDatabase getDb() {
        return db;
    }

    //endregion

    // region   保存登录用户信息，设置鹰眼的EntityName

    /**
     * 保存登录人员信息
     *
     * @param le
     */
    public void setLoginEntity(LoginEntity le, boolean insert) {
        this.loginEntity = le;
        setEntityName(le.getUsername() + "_" + le.getLoginUser().getName());
        if (insert) {
            setLoginInfo(le);
        } else {
            LastLoginService.insert(entityName, new Date());
        }
    }


    private void setLoginInfo(LoginEntity le) {
        String loginInfo = JsonTool.beanToJsonString(le);
        UserService.insert(entityName, loginInfo);
        LastLoginService.insert(entityName, new Date());
    }


    public void setEntityName(String entityName) {
        this.entityName = entityName;
        mTrace.setEntityName(this.entityName);
    }


    public String getEntityName() {
        return this.entityName;
    }

    /**
     * 获取登录信息
     *
     * @return
     */
    public LoginEntity getLoginEntity() {
        return this.loginEntity;
    }


    /**
     * 获取用户的系统认证Token。
     *
     * @return token
     */
    public String getToken() {

        if (null == loginEntity) {
            return "";
        }
        return this.loginEntity.getUserToken().getKey();
    }
    // endregion


    public LatLng getDepartmentLatLng() {
        if (loginEntity != null)
            return new LatLng(Double.parseDouble(loginEntity.getLoginUser().getDepartment().getLat()),
                    Double.parseDouble(loginEntity.getLoginUser().getDepartment().getLng()));
        else
            return null;
    }


}
